import { App } from 'vue'

class MiStorage {
  instance!: Storage

  constructor(type?: string) {
    this.change(type)
  }

  get(keys: string | string[]): any {
    let data: any = {}
    if (Array.isArray(keys)) {
      for (let i = 0, len = keys.length; i < len; i++) {
        const key = keys[i]
        data[key] = JSON.parse(this.instance.getItem(key) ?? 'null')
      }
    } else {
      data = null
      if (keys) data = JSON.parse(this.instance.getItem(keys) ?? 'null')
    }
    return data
  }

  set(key: string, value: any): void {
    this.instance.setItem(key, JSON.stringify(value))
  }

  del(keys: string | string[]) {
    if (Array.isArray(keys)) {
      for (let i = 0, len = keys.length; i < len; i++) {
        const key = keys[i]
        this.instance.removeItem(key)
      }
    } else {
      this.instance.removeItem(keys)
    }
  }

    /**
     * Change storage type.
     * @param type
     */
  change(type?: string) {
    this.instance =
        type === 'local' ? localStorage : type === 'session' ? sessionStorage : localStorage
    return this
  }
}

export const $storage = new MiStorage()
const storage = {
    install(app: App) {
        app.config.globalProperties.$storage = $storage
        return app
    }
}
export default storage
